package org.swift.mashup.engine.model;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Stack;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class OctaveScriptValidator {
	private static final Pattern multilinePattern = Pattern.compile("^(.*)$", Pattern.MULTILINE);
	
	/**
	 * TODO: Move to a properties file.
	 */
	private static final String[] startBlockStatements = new String[]{
		 "if ", "switch ", "while ", "function ", "for ", "unwind_protect ", 
		 "do", "try"
	};
	
	/**
	 * TODO: Move to a properties file.
	 */
	private static final String[] endBlockStatements = new String[]{
		"endif", "endswitch", "endwhile", "endfunction", "endfor",
		"end_unwind_protect", "until", "end_try_catch"
	};
	
	public void validateScript(String script) throws ScriptError {
		Stack<String> blockStatements = new Stack<String>();
		String[] statements =  null;
		for (String line : getLines(script)){
			statements = line.split(";");
			for (String statement : statements){
				statement = statement.trim();
				if (isStartBlock(statement)){
					blockStatements.push(statement);
				} else if (isEndBlock(statement)){
					blockStatements.pop();
				}
			}
		}
		if (blockStatements.size() > 0){
			throw new ScriptError("Missing end of statement block.  Please check your script for completeness.");
		}
	}
	
	private boolean isStartBlock (String command){
		return indexOf_startsWith(startBlockStatements,command) != -1;
	}
	
	private boolean isEndBlock (String command){
		return indexOf(endBlockStatements,command) != -1;
	}
	
	private int indexOf_startsWith (final String[] list, String value){
		for (int i = 0; i < list.length; i++){
			if (value.startsWith(list[i])){
				return i;
			}
		}
		return -1;
	}
	
	private int indexOf (final String[] list, String value){
		for (int i = 0; i < list.length; i++){
			if (list[i].equals(value)){
				return i;
			}
		}
		return -1;
	}
	
	private Collection<String> getLines (String data){
		Collection<String> matches = new ArrayList<String>();
	    Matcher matcher = multilinePattern.matcher(data);
	    while (matcher.find()){
	    	for (int i = 0; i < matcher.groupCount(); i++){
		    	matches.add(matcher.group(i));
		    }
	    }
	    return matches;
	}
}
